import React, { PureComponent } from 'react';
// import { Menu } from 'antd'
import Link from 'umi/link';
import { Tooltip } from 'antd';
import { Icon } from 'react-fa';
import Menu from './Menu';
import { /*isUrl, */ urlToList, getMenuMatches, getFlatMenus } from './utils';

const getIcon = icon => {
  if (typeof icon === 'string') {
    return <Icon name={icon} />;
  }
  return icon;
};

const { Item } = Menu;

export default class BaseMenu extends PureComponent {
  static defaultProps = {
    prefixCls: 'menu',
  };
  getMenu = data => {
    return (data || [])
      .filter(item => !item.hide && item.system === this.props.system)
      .map(item => this.getSubMenuOrItem(item));
  };
  getSubMenuOrItem = item => {
    let path;
    if (item.children && item.children.length) {
      const flatMenus = getFlatMenus(item.children, m => !m.hide);
      const flatArrayMenus = Object.keys(flatMenus).map(key => flatMenus[key]);
      flatArrayMenus.some(v => {
        if (v.selected) {
          path = v.path;
          return true;
        }
        return false;
      });
      // item.children.some(route => {
      // 	if (!route.redirect) {
      // 		path = route.path
      // 		return true
      // 	}
      // 	return false
      // })
      path = path || (flatArrayMenus.length ? flatArrayMenus[0].path : item.path);
    }
    path = path || item.path;

    const link = (
      <Link to={path} className="ico-nav" replace>
        {getIcon(item.icon)}
        <span className="ico-text">{item.name}</span>
      </Link>
    );

    const { tooltip } = this.props;

    return (
      <Item key={item.key || item.path}>
        {tooltip ? (
          <Tooltip title={item.title || item.name} placement="right">
            {link}
          </Tooltip>
        ) : (
          link
        )}
      </Item>
    );
  };
  getSelectedMenuKeys = pathname => {
    const { flatMenuKeys, flatMenus } = this.props;
    let keys = urlToList(pathname)
      .map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop())
      .filter(item => item);

    if (keys.length) {
      const routes = keys.map(key => flatMenus[key]).filter(item => item.hide);
      // 隐藏路由时，为选中selectedKeys设置为其rootKey属性，匹配key || path属性
      if (routes.length) {
        return routes.map(route => route.rootKey || route.key || route.path);
      }
    }
    return keys;
  };
  render() {
    const {
      menu,
      location: { pathname },
    } = this.props;

    const selectedKeys = this.getSelectedMenuKeys(pathname);

    return <Menu selectedKeys={selectedKeys}>{this.getMenu(menu)}</Menu>;
  }
}
